package com.neusoft.databus.core.repository.impl;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.databus.common.enums.PhysicalConnType;
import com.neusoft.databus.common.model.Gateway;
import com.neusoft.databus.common.model.QGateway;
import com.neusoft.databus.common.model.QResource;
import com.neusoft.databus.core.repository.CustomizedGatewayRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

/**
 * description
 *
 * @author sunchf
 * @date 2018年12月17日 下午3:32:14
 */
public class CustomizedGatewayRepositoryImpl extends AbstractRepository implements CustomizedGatewayRepository {

    @Override
    public Page<Gateway> search(Pageable pageable, Searchable searchable) {
        final QGateway qGateway = QGateway.gateway;
        final QResource qResource = QResource.resource;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Gateway> query = this.query().selectFrom(qGateway);
        if (searchable.hasKey("resourceCode")) {
            query.innerJoin(qGateway.resources, qResource)
                    .where(qResource.code.eq(searchable.getStrValue("resourceCode")));
        }
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    public List<Gateway> search(Searchable searchable) {
        final QGateway qGateway = QGateway.gateway;
        final QResource qResource = QResource.resource;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Gateway> query = this.query().selectFrom(qGateway);
        if (searchable.hasKey("resourceCode")) {
            query.innerJoin(qGateway.resources, qResource)
                    .where(qResource.code.eq(searchable.getStrValue("resourceCode")));
        }
        query.where(where);
        return query.fetch();
    }

    @Override
    protected Class<?> getModelClass() {
        return Gateway.class;
    }

    private BooleanBuilder buildWhere(Searchable searchable) {
        final QGateway qGateway = QGateway.gateway;
        final BooleanBuilder where = new BooleanBuilder();
        where.and(super.containsStr(qGateway.name, searchable, "name"));
        where.and(super.containsStr(qGateway.code, searchable, "code"));
        where.and(super.equalsBool(qGateway.disabled, searchable, "disabled"));
        where.and(super.equalsEnum(qGateway.physicalConnType, searchable, "physicalConnType",
                (String s) -> PhysicalConnType.valueOf(s)));
        return where;
    }
}
